// 定义活动数据的接口，增强代码可读性和健壮性
interface ExtraInfo {
  label: string;
  value: string;
}

interface Activity {
  id: number;
  name: string;
  type: '回收' | '引流' | '线下' | '闲置';
  rules: string;
  startTime: string;
  endTime: string;
  adId?: string; // 可选字段
  status: 'enable' | 'disable' | 'finished';
  extraInfo?: ExtraInfo[]; // 可扩展信息
  // --- 以下为前端UI控制字段 ---
  expanded?: boolean; // 是否展开详情
  enabling?: boolean; // 是否正在启用
  disabling?: boolean; // 是否正在禁用
  deleting?: boolean; // 是否正在删除
}

Page({
  data: {
    loading: true, // 页面初始加载
    activityList: [] as Activity[], // 活动列表
    // 用于将后端状态映射为 Vant Tag 的类型和文本
    statusMap: {
      enable: { text: '进行中', type: 'success' },
      disable: { text: '已禁用', type: 'warning' },
      finished: { text: '已结束', type: 'primary' },
    },
    // --- 用于编辑弹窗的状态 ---
    showEditPopup: false, // 控制弹窗显示
    editingActivity: {} as Partial<Activity>, // 存储正在编辑的活动数据
    editingIndex: -1, // 正在编辑的活动在列表中的索引
    isSaving: false, // 控制“确认修改”按钮的loading状态
    // --- 颜色变量，用于JS中 ---
    colorTheme: '#19be6b',
    colorDanger: '#f56c6c',
  },

  onLoad() {
    this.fetchActivityList();
  },

  onPullDownRefresh() {
    this.fetchActivityList(true);
  },

  /**
   * 模拟获取活动列表数据
   * @param isRefresh - 是否为下拉刷新
   */
  async fetchActivityList(isRefresh = false) {
    if (!isRefresh) {
      this.setData({ loading: true });
    } else {
      wx.showNavigationBarLoading();
    }

    // --- 模拟API请求 ---
    await new Promise(resolve => setTimeout(resolve, 1000));
    const mockData: Activity[] = [
      {
        id: 1,
        name: '夏季数码产品回收节',
        type: '回收',
        rules: '1. 仅限指定品牌手机、电脑。\n2. 回收价格以现场评估为准。',
        startTime: '2024-07-01',
        endTime: '2024-07-31',
        adId: 'AD10086',
        status: 'enable',
        extraInfo: [
          { label: '参与条件', value: '小程序注册用户均可参与' },
          { label: '奖励说明', value: '成功回收后，额外赠送100积分' }
        ]
      },
      {
        id: 2,
        name: '新用户注册引流活动',
        type: '引流',
        rules: '新用户注册即可获得优惠券一张。',
        startTime: '2024-06-15',
        endTime: '2024-08-15',
        status: 'disable',
      },
      {
        id: 3,
        name: '线下社区闲置交换',
        type: '线下',
        rules: '每周六下午在XX社区中心举办。',
        startTime: '2024-05-01',
        endTime: '2024-05-31',
        status: 'finished',
      }
    ];
    // -----------------

    // 给每个列表项添加前端控制字段
    const processedList = mockData.map(item => ({
      ...item,
      expanded: false,
      enabling: false,
      disabling: false,
      deleting: false,
    }));
    
    this.setData({
      activityList: processedList,
      loading: false,
    });

    if (isRefresh) {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }
  },

  /**
   * 切换详情的展开/收起
   */
  toggleDetails(e: WechatMiniprogram.TouchEvent) {
    const index = e.currentTarget.dataset.index as number;
    const key = `activityList[${index}].expanded`;
    this.setData({
      [key]: !this.data.activityList[index].expanded
    });
  },

  /**
   * 统一的操作处理函数
   */
  async _handleAction(
    id: number,
    index: number,
    action: 'enable' | 'disable' | 'delete',
    loadingKey: 'enabling' | 'disabling' | 'deleting',
    confirmTitle: string,
    confirmContent: string,
    successToast: string
  ) {
    const res = await wx.showModal({
      title: confirmTitle,
      content: confirmContent,
      confirmColor: action === 'delete' ? this.data.colorDanger : this.data.colorTheme,
    });

    if (res.confirm) {
      this.setData({ [`activityList[${index}].${loadingKey}`]: true });

      await new Promise(resolve => setTimeout(resolve, 800));

      let updatedList = [...this.data.activityList];
      if (action === 'delete') {
        updatedList.splice(index, 1);
      } else {
        updatedList[index].status = action === 'enable' ? 'enable' : 'disable';
      }
      
      if (updatedList[index]) {
        updatedList[index][loadingKey] = false;
      }
      this.setData({ activityList: updatedList });

      wx.showToast({ title: successToast, icon: 'none' });
    }
  },

  handleEnable(e: WechatMiniprogram.TouchEvent) {
    const { id, index } = e.currentTarget.dataset;
    this._handleAction(id, index, 'enable', 'enabling', '确认启用', `你确定要启用活动【${this.data.activityList[index].name}】吗？`, '启用成功');
  },

  handleDisable(e: WechatMiniprogram.TouchEvent) {
    const { id, index } = e.currentTarget.dataset;
    this._handleAction(id, index, 'disable', 'disabling', '确认禁用', `你确定要禁用活动【${this.data.activityList[index].name}】吗？`, '禁用成功');
  },

  handleDelete(e: WechatMiniprogram.TouchEvent) {
    const { id, index } = e.currentTarget.dataset;
    this._handleAction(id, index, 'delete', 'deleting', '危险操作', `你确定要永久删除活动【${this.data.activityList[index].name}】吗？此操作不可恢复！`, '删除成功');
  },
  
  /**
   * 显示编辑弹窗
   */
  showEditPopup(e: WechatMiniprogram.TouchEvent) {
    const { index } = e.currentTarget.dataset;
    const activityToEdit = this.data.activityList[index];

    this.setData({
      editingActivity: JSON.parse(JSON.stringify(activityToEdit)),
      editingIndex: index,
      showEditPopup: true,
    });
  },

  /**
   * 关闭编辑弹窗
   */
  closeEditPopup() {
    this.setData({
      showEditPopup: false,
    });
  },
  
  /**
   * 监听表单字段变化，并更新 editingActivity
   */
  onFieldChange(e: WechatMiniprogram.Input) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail;
    this.setData({
      [`editingActivity.${field}`]: value,
    });
  },

  /**
   * 处理保存编辑
   */
  async handleSaveEdit() {
    if (!this.data.editingActivity.name) {
      wx.showToast({ title: '活动名称不能为空', icon: 'none' });
      return;
    }

    this.setData({ isSaving: true });

    console.log('正在保存的数据:', this.data.editingActivity);
    await new Promise(resolve => setTimeout(resolve, 800));

    const { editingIndex, editingActivity } = this.data;
    const key = `activityList[${editingIndex}]`;
    
    this.setData({
      [key]: editingActivity,
      isSaving: false,
    });
    
    this.closeEditPopup();
    
    wx.showToast({
      title: '修改成功',
      icon: 'none',
    });
  },
});
